package com.authine.cloudpivot.ext.controller.archives;

import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkItemModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
import com.authine.cloudpivot.ext.Utils.CustomSchemaCode;
import com.authine.cloudpivot.ext.service.CloudSqlService;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author fengjie
 * @version 1.0.0
 * @ClassName ContactUnitFilesController
 * @Description 往来单位档案点检记录
 * @createTime 2023/2/2 8:43
 */
@RestController
@RequestMapping("/public/unit")
@Slf4j
public class ContactUnitFilesController extends BaseController {
    @Autowired
    CloudSqlService sqlService;

    /**
     * 【总公司级往来单位档案总公司点检汇总记录】审批完成后，数据同步到【总公司级往来单位档案总公司点检汇总记录 基础表】
     */
    @RequestMapping("finishToOfficeUnitBase1")
    public void finishToOfficeUnitBase1(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.HEAD_OFFICE_UNIT_1, bizId);
        // 相关档案明细表
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(CustomSchemaCode.HEAD_OFFICE_UNIT_DETAIL1);

        String approval = getFileBaseInfoWorkFlowApproval(bizObject);
        //
        for (Map<String, Object> map : list) {
            try {
                Map<String, Object> data = fileInfoBaseMap(bizObject, map, approval);
                // 判断是否已存在
                String id = existsBizObject(data, CustomSchemaCode.OFFICE_UNIT_BASE_1);
                if (StringUtils.isNotEmpty(id)) {
                    data.put("id", id);
                }
                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.OFFICE_UNIT_BASE_1, data, false);
                model.setSequenceStatus(SequenceStatus.COMPLETED.name());
                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                log.info("总公司级往来单位档案总公司点检汇总记录 基础表数据新增成功");
                // 调用存储过程
                callHeadOfficeUnit1Process(id);
            } catch (Exception e) {
                log.info("总公司级往来单位档案总公司点检汇总记录 基础表数据维护失败，报错信息：{}", e.getMessage());
                log.info("总公司级往来单位档案总公司点检汇总记录 基础表数据操作失败 往来单位代码={}", map.get("functionCode"));
            }
        }
    }

    /**
     * 【总公司级往来单位档案公司点检汇总记录】审批完成后，数据同步到【总公司级往来单位档案公司点检汇总记录 基础表】
     */
    @RequestMapping("finishToOfficeUnitBase2")
    public void finishToOfficeUnitBase2(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.HEAD_OFFICE_UNIT_2, bizId);
        // 相关档案明细表
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(CustomSchemaCode.HEAD_OFFICE_UNIT_DETAIL2);

        String approval = getFileBaseInfoWorkFlowApproval(bizObject);
        //
        for (Map<String, Object> map : list) {
            try {/**/
                Map<String, Object> data = fileInfoBaseMap(bizObject, map, approval);
                // 判断是否已存在
                String id = existsBizObject(data, CustomSchemaCode.OFFICE_UNIT_BASE_2);
                if (StringUtils.isNotEmpty(id)) {
                    data.put("id", id);
                }
                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.OFFICE_UNIT_BASE_2, data, false);
                model.setSequenceStatus(SequenceStatus.COMPLETED.name());
                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                log.info("总公司级往来单位档案公司点检汇总记录 基础表数据新增成功");

                // 调用存储过程
                callHeadOfficeUnit2Process(id);
            } catch (Exception e) {
                log.info("总公司级往来单位档案公司点检汇总记录 基础表数据维护失败，报错信息：{}", e.getMessage());
                log.info("总公司级往来单位档案公司点检汇总记录 基础表数据操作失败 往来单位代码={}", map.get("functionCode"));
            }
        }
    }

    /**
     * 【公司往来单位档案点检汇总记录】审批完成后，数据同步到【公司往来单位档案点检汇总记录 基础表】
     */
    @RequestMapping("finishToCompanyUnitBase")
    public void finishToCompanyUnitBase(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.COMPANY_UNIT, bizId);
        // 相关档案明细表
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(CustomSchemaCode.COMPANY_UNIT_DETAIL);

        String approval = getFileBaseInfoWorkFlowApproval(bizObject);
        //
        for (Map<String, Object> map : list) {
            try {/**/
                Map<String, Object> data = fileInfoBaseMap(bizObject, map, approval);
                // 判断是否已存在
                String id = existsBizObject(data, CustomSchemaCode.COMPANY_UNIT_BASE);
                if (StringUtils.isNotEmpty(id)) {
                    data.put("id", id);
                }
                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.COMPANY_UNIT_BASE, data, false);
                model.setSequenceStatus(SequenceStatus.COMPLETED.name());
                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                log.info("公司往来单位档案点检汇总记录 基础表数据新增成功");

                // 调用存储过程
                callCompanyUnitProcess(id);
            } catch (Exception e) {
                log.info("公司往来单位档案点检汇总记录 基础表数据维护失败，报错信息：{}", e.getMessage());
                log.info("公司往来单位档案点检汇总记录 基础表数据操作失败 往来单位={}", map.get("functionCode"));
            }
        }
    }

    /**
     * 调用存储过程
     * ------公司级往来单位档案点检汇总表
     * exec   SyncComSuppACS
     */
    private void callCompanyUnitProcess(String bizId) {
        if (StringUtils.isEmpty(bizId)) {
            return;
        }
        // 编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.COMPANY_UNIT_BASE);
        StringBuilder sql = new StringBuilder("SELECT * from ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        // 查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());

        log.info("入参map={}", map);

        // 调用存储过程
        String companyCode = MapUtils.getString(map, "companyCode", "");// 公司代码
        String functionCode = MapUtils.getString(map, "functionCode", "");// 往来单位代码
        String bj = MapUtils.getString(map, "bj", "");
        String bg = MapUtils.getString(map, "bg", "");
        String ry = MapUtils.getString(map, "ry", "");
        String lzry = MapUtils.getString(map, "lzry", "");
        String yw = MapUtils.getString(map, "yw", "");
        String wt = MapUtils.getString(map, "wt", "");
        String fw = MapUtils.getString(map, "fw", "");
        String da = MapUtils.getString(map, "da", "");
        String sx = MapUtils.getString(map, "sx", "");
        String jl = MapUtils.getString(map, "jl", "");
        String zz = MapUtils.getString(map, "zz", "");
        String dc = MapUtils.getString(map, "dc", "");
        String wl = MapUtils.getString(map, "wl", "");
        String bm = MapUtils.getString(map, "bm", "");
        String ht = MapUtils.getString(map, "ht", "");
        String txdn = MapUtils.getString(map, "txdn", "");
        String kc = MapUtils.getString(map, "kc", "");
        String zxda = MapUtils.getString(map, "zxda", "");
        String sdsjl = MapUtils.getString(map, "sdsjl", "");
        String zy = MapUtils.getString(map, "zy", "");
        String zb = MapUtils.getString(map, "zb", "");
        String tb = MapUtils.getString(map, "tb", "");
        String jh = MapUtils.getString(map, "jh", "");
        String swxy = MapUtils.getString(map, "swxy", "");
        String bz = MapUtils.getString(map, "bz", "");
        String empower = MapUtils.getString(map, "empower", "");
        String jobDescription = MapUtils.getString(map, "jobDescription", "");// 工作说明
        String auditer = MapUtils.getString(map, "auditer", "");// 审批人

        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncComSuppACS '%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s'",
                companyCode,functionCode,bj,bg,ry,lzry,yw,wt,fw,da,sx,jl,zz,dc,wl,bm,ht,txdn,kc,zxda,sdsjl,zy,zb,tb,jh,swxy,bz,empower,jobDescription,auditer);
        log.info("\n==========准备调用存储过程:{}", execSql);
        sqlService.execute(CloudSqlService.htEas, execSql);
        log.info("\n=============存储过程执行完成");
    }

    /**
     * 调用存储过程
     * ------总公司级往来单位档案  公司  点检汇总表
     * exec   SyncComCorpSuppACS
     */
    private void callHeadOfficeUnit2Process(String bizId) {
        if (StringUtils.isEmpty(bizId)) {
            return;
        }
        // 编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.OFFICE_UNIT_BASE_2);
        StringBuilder sql = new StringBuilder("SELECT * from ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        // 查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());

        log.info("入参map={}", map);

        // 调用存储过程
        String companyCode = MapUtils.getString(map, "companyCode", "");// 公司代码
        String functionCode = MapUtils.getString(map, "functionCode", "");// 往来单位代码
        String empower = MapUtils.getString(map, "empower", "");
        String jobDescription = MapUtils.getString(map, "jobDescription", "");// 工作说明
        String auditer = MapUtils.getString(map, "auditer", "");// 审批人

        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncComCorpSuppACS '%s','%s','%s','%s','%s'",
                companyCode, functionCode, empower, jobDescription, auditer);
        log.info("\n==========准备调用存储过程:{}", execSql);
        sqlService.execute(CloudSqlService.htEas, execSql);
        log.info("\n=============存储过程执行完成");
    }

    /**
     * 调用存储过程
     * ------总公司级往来单位档案  总公司  点检汇总表
     * exec   SyncCorpSuppACS
     */
    private void callHeadOfficeUnit1Process(String bizId) {
        if (StringUtils.isEmpty(bizId)) {
            return;
        }
        // 编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.OFFICE_UNIT_BASE_1);
        StringBuilder sql = new StringBuilder("SELECT * from ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        // 查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());

        log.info("入参map={}", map);

        // 调用存储过程
        String functionCode = MapUtils.getString(map, "functionCode", "");// 往来单位代码
        String bj = MapUtils.getString(map, "bj", "");
        String bg = MapUtils.getString(map, "bg", "");
        String ry = MapUtils.getString(map, "ry", "");
        String lzry = MapUtils.getString(map, "lzry", "");
        String yw = MapUtils.getString(map, "yw", "");
        String wt = MapUtils.getString(map, "wt", "");
        String fw = MapUtils.getString(map, "fw", "");
        String da = MapUtils.getString(map, "da", "");
        String sx = MapUtils.getString(map, "sx", "");
        String jl = MapUtils.getString(map, "jl", "");
        String zz = MapUtils.getString(map, "zz", "");
        String dc = MapUtils.getString(map, "dc", "");
        String wl = MapUtils.getString(map, "wl", "");
        String bm = MapUtils.getString(map, "bm", "");
        String ht = MapUtils.getString(map, "ht", "");
        String txdn = MapUtils.getString(map, "txdn", "");
        String kc = MapUtils.getString(map, "kc", "");
        String zxda = MapUtils.getString(map, "zxda", "");
        String sdsjl = MapUtils.getString(map, "sdsjl", "");
        String zy = MapUtils.getString(map, "zy", "");
        String zb = MapUtils.getString(map, "zb", "");
        String tb = MapUtils.getString(map, "tb", "");
        String jh = MapUtils.getString(map, "jh", "");
        String swxy = MapUtils.getString(map, "swxy", "");
        String bz = MapUtils.getString(map, "bz", "");
        String empower = MapUtils.getString(map, "empower", "");
        String jobDescription = MapUtils.getString(map, "jobDescription", "");// 工作说明
        String auditer = MapUtils.getString(map, "auditer", "");// 审批人

        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncCorpSuppACS '%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s'",
                functionCode,bj,bg,ry,lzry,yw,wt,fw,da,sx,jl,zz,dc,wl,bm,ht,txdn,kc,zxda,sdsjl,zy,zb,tb,jh,swxy,bz,empower,jobDescription,auditer);
        log.info("\n==========准备调用存储过程:{}", execSql);
        sqlService.execute(CloudSqlService.htEas, execSql);
        log.info("\n=============存储过程执行完成");
    }

    /**
     * 查询审批人,返回  员工号+姓名
     *
     * @param bizObject
     * @return
     */
    private String getFileBaseInfoWorkFlowApproval(BizObjectCreatedModel bizObject) {
        WorkflowInstanceModel instanceModel = getWorkflowInstanceFacade().getByObjectId(bizObject.getId());
        List<WorkItemModel> workItems = getWorkflowInstanceFacade().getWorkItems(instanceModel.getId(), true);
        final String finalActivityCode = "Activity8";
        Optional<WorkItemModel> first = workItems.stream().filter(a -> a.getActivityCode().equals(finalActivityCode)).findFirst();
        String participant = null;
        if (first.isPresent()) {
            participant = first.get().getParticipant();
        }
        if (participant == null) {
            participant = bizObject.getCreater().getId();
        }
        UserModel user = getOrganizationFacade().getUser(participant);
        return new StringBuilder(user.getEmployeeNo()).append("　").append(user.getName()).toString();
    }


    /**
     * 判断是否已存在
     *
     * @return
     */
    private String existsBizObject(Map data, String schemaCode) {

        String tableName = getBizObjectFacade().getTableName(schemaCode);

        StringBuilder sql = new StringBuilder("select id  from ").append(tableName)
                .append(" where functionCode='").append(data.get("functionCode")).append("'")
                .append(";");
        Map<String, Object> map = sqlService.getMap(sql.toString());
        return (String) map.get("id");
    }

    /**
     * 设置基础表数据
     *
     * @param bizObject 主表数据
     * @param map       子表数据
     * @param auditer   审批人
     * @return
     */
    public static Map<String, Object> fileInfoBaseMap(BizObjectCreatedModel bizObject, Map<String, Object> map, String auditer) {
        // 审批人,审批时间
        map.put("applicant", bizObject.get("applicant"));
        map.put("auditer", auditer);
        map.put("time", new Date());
        map.remove("rowStatus");
        map.remove("id");
        return map;
    }
}
